import dayjs, { Dayjs } from 'dayjs';
import { Duration } from 'dayjs/plugin/duration';

export const DEFAULT_TIMEZONE: string = 'Asia/Shanghai';
export const DURATION_NOW = 'NOW';
export const DURATION_P7D = 'P7D';
export const DURATION_P30D = 'P30D';
export const DURATION_P90D = 'P90D';

export const Y_M_D: string = 'YYYY-MM-DD';
export const M_D: string = 'M/D';
export const Y_M_D_H_M: string = 'YYYY-MM-DD HH:mm';
export const Y_M_D_H_M_S = 'YYYY-MM-DD HH:mm:ss';
export const H_M: string = 'HH:mm';

export const fromISO8601 = (iso8601Dt: string | undefined | null): Dayjs | undefined => {
  if (!iso8601Dt) {
    return undefined;
  }
  return dayjs(iso8601Dt).tz(DEFAULT_TIMEZONE);
};

export const formatISO8601 = (iso8601Dt: string | undefined | null, format?: string): string => {
  return fromISO8601(iso8601Dt)?.format(format ?? Y_M_D) ?? '';
};

export const asDays = (duration: Duration | string | undefined | null): number | null => {
  if (!duration) {
    return null;
  }
  if (typeof duration === 'string') {
    try {
      return dayjs.duration(duration as string).asDays();
    } catch (e) {
      console.log('invalid duration', e);
      return null;
    }
  }
  return (duration as Duration).asDays();
};
